package com.vhans.db.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.vhans.core.domain.CRequest;
import com.vhans.core.utils.BeanCopyUtils;
import com.vhans.core.utils.StringUtils;
import com.vhans.db.mapper.CRequestMapper;
import com.vhans.db.model.dto.ConditionDTO;
import com.vhans.db.model.dto.request.RequestDTO;
import com.vhans.db.model.vo.request.RequestInfoVO;
import com.vhans.db.model.vo.request.RequestVO;
import com.vhans.db.service.ICRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 好友请求Service业务层处理
 *
 * @author vhans
 * @date 2023-05-21
 */
@Service("cRequestServiceImpl")
public class CRequestServiceImpl implements ICRequestService {
    @Autowired
    private CRequestMapper requestMapper;

    @Override
    public List<RequestVO> selectRequestVOList(ConditionDTO condition) {
        // 查询好友请求信息
        return requestMapper.selectRequestVOList(condition);
    }

    @Override
    public RequestInfoVO selectRequestInfoById(Integer id) {
        // 查询好友请求信息
        RequestInfoVO cRequestInfoVO = requestMapper.selectRequestInfoById(id);
        Assert.notNull(cRequestInfoVO, "没有该好友请求");
        // 下面可以扩展信息delete
        return cRequestInfoVO;
    }

    @Override
    public int deleteRequestByIdIdList(List<Integer> idList) {
        // 删除好友请求
        return requestMapper.deleteBatchIds(idList);
    }

    @Override
    public List<RequestVO> selectUserRequestVOList() {
        int userId = StpUtil.getLoginIdAsInt();
        return requestMapper.selectUserRequestVOList(userId);
    }

    @Override
    public List<RequestVO> selectIRequestVOList() {
        int userId = StpUtil.getLoginIdAsInt();
        return requestMapper.selectIRequestVOList(userId);
    }

    @Override
    public void changeFriendRequestStatus(Integer requestId, Integer status) {
        requestMapper.updateById(CRequest.builder()
                .id(requestId)
                .requestStatus(status).build());
    }

    @Override
    public CRequest insertRequest(RequestDTO requestDTO) {
        CRequest request = requestMapper.selectOne(new LambdaQueryWrapper<CRequest>()
                .select(CRequest::getId)
                .eq(CRequest::getRoomId, requestDTO.getRoomId())
                .eq(CRequest::getRequestStatus, 0));
        if (request == null) {
            // 要添加的好友请求
            CRequest newCRequest = BeanCopyUtils.copyBean(requestDTO, CRequest.class);
            requestMapper.insert(newCRequest);
            return newCRequest;
        }
        return null;
    }
}
